<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑教师' : '添加教师' }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" :placeholder="isEdit ? '不填则保持原密码' : ''" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="所属学校" prop="schoolId">
          <el-select v-model="form.schoolId" placeholder="请选择学校" style="width: 100%">
            <el-option
              v-for="item in schoolOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="教育阶段" prop="educationLevel">
          <el-select v-model="form.educationLevel" placeholder="请选择教育阶段" style="width: 100%" @change="handleEducationLevelChange">
            <el-option :key="1" label="小学" :value="1" />
            <el-option :key="2" label="初中" :value="2" />
            <el-option :key="3" label="高中" :value="3" />
            <el-option :key="4" label="大学" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="任教学科" prop="subjectIds">
          <el-select v-model="form.subjectIds" placeholder="请选择学科" style="width: 100%" multiple>
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="uploadAvatar"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.avatar" :src="form.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="avatar-tip">建议上传正方形图片，大小不超过2MB</div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { addTeacher, updateTeacher, getTeacherDetail } from '@/api/teacher';
import { getSchoolList } from '@/api/school';
import { getAllSubjects } from '@/api/subject';
import { uploadFile } from '@/api/file';

export default {
  name: 'TeacherEdit',
  data() {
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('手机号格式不正确'));
      } else {
        callback();
      }
    };
    return {
      form: {
        id: undefined,
        username: '',
        password: '',
        nickname: '',
        email: '',
        phone: '',
        avatar: '',
        schoolId: undefined,
        educationLevel: undefined,
        subjectIds: []
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        schoolId: [
          { required: true, message: '请选择所属学校', trigger: 'change' }
        ],
        educationLevel: [
          { required: true, message: '请选择教育阶段', trigger: 'change' }
        ],
        subjectIds: [
          { required: true, type: 'array', message: '请选择至少一个学科', trigger: 'change' }
        ]
      },
      loading: false,
      schoolOptions: [],
      allSubjects: [], // 所有学科
      subjectOptions: [] // 当前教育阶段可选的学科
    };
  },
  computed: {
    isEdit() {
      return this.$route.params.id !== undefined;
    }
  },
  created() {
    this.getSchools();
    this.getSubjects();
    if (this.isEdit) {
      this.getDetail();
    } else {
      // 添加模式下密码是必填
      this.rules.password.unshift({ required: true, message: '请输入密码', trigger: 'blur' });
    }
  },
  methods: {
    getDetail() {
      getTeacherDetail(this.$route.params.id)
        .then(response => {
          this.form = response.data;
          this.filterSubjectsByLevel(this.form.educationLevel);
        })
        .catch(() => {
          this.$message.error('获取教师信息失败');
          this.goBack();
        });
    },
    getSchools() {
      getSchoolList(1, 100) // 获取第1页，最多100个学校
        .then(response => {
          const schools = response.data.records;
          this.schoolOptions = schools.map(school => ({
            value: school.id,
            label: school.name
          }));
        })
        .catch(() => {
          this.$message.error('获取学校列表失败');
        });
    },
    getSubjects() {
      getAllSubjects()
        .then(response => {
          this.allSubjects = response.data;
        })
        .catch(() => {
          this.$message.error('获取学科列表失败');
        });
    },
    handleEducationLevelChange(level) {
      this.filterSubjectsByLevel(level);
      // 清空已选学科
      this.form.subjectIds = [];
    },
    filterSubjectsByLevel(level) {
      if (!level) return;
      
      const filteredSubjects = this.allSubjects.filter(subject => subject.level === level);
      this.subjectOptions = filteredSubjects.map(subject => ({
        value: subject.id,
        label: subject.name
      }));
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true;
          const action = this.isEdit ? updateTeacher : addTeacher;
          action(this.form)
            .then(() => {
              this.$message({
                message: this.isEdit ? '更新成功' : '添加成功',
                type: 'success'
              });
              this.goBack();
            })
            .catch(() => {
              this.$message.error(this.isEdit ? '更新失败' : '添加失败');
            })
            .finally(() => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    goBack() {
      this.$router.push('/teachers');
    },
    uploadAvatar(options) {
      const { file } = options;
      this.loading = true;
      uploadFile(file)
        .then(response => {
          this.form.avatar = response.data.url;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          this.$message.error('上传头像失败');
        });
    },
    handleAvatarSuccess(res, file) {
      // 实际项目中，这里应该使用后端返回的URL
      this.form.avatar = res.url || URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.avatar-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}
</style> 